package com.jeomo.common.core.util;

import cn.hutool.poi.excel.ExcelWriter;
import com.jeomo.common.core.annocation.ExcelHeader;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

/**
 * <h3>jeomo</h3>
 * <p>excel工具类</p>
 *
 * @author : qibotian
 * @date : 2020-11-23 15:53
 **/
@Component
public class ExcelUtil extends cn.hutool.poi.excel.ExcelUtil {

    /**
     * @param response 返回对象
     * @param voList   返回前端的VO实体
     * @description: 导出Excel
     * @return: void
     * @author: 崔贺
     * @time: 2020/12/1 10:45
     */
    public <T> void export(HttpServletResponse response, List<T> voList) {
        // 通过工具类创建writer，默认创建xls格式
        try (ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter()) {
            for (T vo : voList) {
                Class<?> clz = vo.getClass();
                Field[] fields = clz.getDeclaredFields();
                for (Field field : fields) {
                    boolean fieldAnnotationPresent = field.isAnnotationPresent(ExcelHeader.class);
                    if (fieldAnnotationPresent) {
                        ExcelHeader headerName = field.getAnnotation(ExcelHeader.class);
                        //自定义标题别名
                        String name = field.getName();
                        writer.addHeaderAlias(name, headerName.value());
                    }
                }
            }
            // 合并单元格后的标题行，使用默认标题样式
//        int length = 0;
//        if (!list.isEmpty()) {
//            length = list.get(0).getClass().getDeclaredFields().length;
//        }
//        writer.merge(length - 1, titleName);
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(voList, true);
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
//            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //此处记得关闭输出Servlet流
//        IoUtil.close(out);

    }

}
